package cn.chinaunicom.mini.program.dingtalk.openapi.service;

import cn.chinaunicom.mini.program.dingtalk.openapi.client.IDingTalkClient;
import com.aliyun.dingtalkrobot_1_0.models.*;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiImChatScencegroupMessageSendV2Request;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiImChatScencegroupMessageSendV2Response;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ProjectName: dingtalk-adapter
 * @Package: cn.chinaunicom.mini.program.dingtalk.openapi.service
 * @ClassName: DingTalkRobotAPI
 * @Description: java类作用描述
 * @Author: wangjc
 * @CreateDate: 2024/7/3
 * @UpdateUser: wangjc
 * @UpdateDate: 2024/7/3
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
@Slf4j
@Component
public class DingTalkRobotAPI {

    /**
     * 发送企业群消息
     * 该方法用于通过钉钉机器人接口发送企业群消息。使用提供的访问令牌和群消息请求对象，通过调用钉钉机器人API来发送消息。
     * 如果发送消息失败，将会记录错误日志。
     *
     * @param orgGroupSendRequest 群消息请求对象，包含发送消息的具体内容和配置。
     * @param accessToken 访问令牌，用于授权验证。
     * @return 返回消息发送的响应体，如果发送失败则返回null。
     */
    public OrgGroupSendResponseBody sendOrgGroupMessage(com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendRequest orgGroupSendRequest, String accessToken) {
        try {
            // 创建钉钉机器人客户端
            com.aliyun.dingtalkrobot_1_0.Client client = this.createClient();

            // 设置请求头，包含访问令牌
            com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendHeaders orgGroupSendHeaders = new com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendHeaders();
            orgGroupSendHeaders.xAcsDingtalkAccessToken = accessToken;

            // 调用钉钉机器人接口发送消息，并获取响应
            OrgGroupSendResponse response = client.orgGroupSendWithOptions(orgGroupSendRequest, orgGroupSendHeaders, new RuntimeOptions());

            // 返回消息发送的响应体
            return response.getBody();
        } catch (Exception e) {
            // 记录发送消息失败的日志
            log.error("发送群消息失败", e);
        }
        // 如果发送消息失败，返回null
        return null;
    }

    public String sendCustomMessage(OapiRobotSendRequest req, String accessToken) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send");
        OapiRobotSendResponse rsp = client.execute(req, "access_token");
        System.out.println(rsp.getBody());
        return rsp.getBody();
    }

    public OrgGroupQueryResponseBody queryReaderList(OrgGroupQueryRequest orgGroupQueryRequest, String accessToken) {
        OrgGroupQueryHeaders orgGroupQueryHeaders = new OrgGroupQueryHeaders();
        orgGroupQueryHeaders.xAcsDingtalkAccessToken = accessToken;
        orgGroupQueryRequest
                .setOpenConversationId("cid6KeBBLoveMJOGXoYKF5x7EeiodoA==")
                .setRobotCode("dingue4kfzdxbyn0pjqd")
                .setProcessQueryKey("Kna29Ra5pdJznx1ghavbumkQKwDzgfxZLapw55G7x0Q=")
                .setMaxResults(50L)
                .setNextToken("50");
        try {
            com.aliyun.dingtalkrobot_1_0.Client client = this.createClient();
            OrgGroupQueryResponse rsp = client.orgGroupQueryWithOptions(orgGroupQueryRequest, orgGroupQueryHeaders, new RuntimeOptions());
            return rsp.getBody();
        } catch (Exception e) {
            log.error("查询群成员已读列表失败", e);
        }
        return null;
    }


    public String sendTemplateMessage(OapiImChatScencegroupMessageSendV2Request req, String accessToken) throws ApiException {
        req.setMsgTemplateId("inner_app_template_markdown");
        req.setIsAtAll(false);
        req.setMsgParamMap("{\"title\":\"测试\",\"markdown_content\":\"# 测试内容 \n @180xxxx3120\"}");
        req.setMsgMediaIdParamMap("{\"pic1\":\"@123\",\"pic2\":\"@456\"}");
        req.setTargetOpenConversationId("cid9FTRQSLo+sK*****==");
        req.setAtMobiles("137*****000");
        req.setAtUsers("072*****");
        req.setReceiverUserIds("072*****,manager422*****");
        req.setReceiverUnionIds("jHs*****,atc*****");
        req.setRobotCode("fTv5O*****");
        OapiImChatScencegroupMessageSendV2Response rsp = IDingTalkClient.execute("https://oapi.dingtalk.com/topapi/im/chat/scencegroup/message/send_v2", req, accessToken);
        System.out.println(rsp.getBody());
        return rsp.getBody();
    }
    /**
     * 使用 Token 初始化账号Client
     * @return Client
     * @throws Exception
     */
    private com.aliyun.dingtalkrobot_1_0.Client createClient() throws Exception {
        return new com.aliyun.dingtalkrobot_1_0.Client(IDingTalkClient.genDingTalkClientConfig());
    }
}
